var mongoose = require('mongoose');

/*
 * Mongo DB connection configuration
 */
var MessengerDB = {
	HOST: 'db.304lab.net',
	NAME: 'muchine',
	HISTORY: 'messenger.history',
};

var db = mongoose.createConnection(MessengerDB.HOST, MessengerDB.NAME);

//handle db connection event
db.on('error', console.error.bind(console, 'connection error.'));
db.on('open', function() {
	console.log('connected to ' + MessengerDB.NAME + ' database on ' + MessengerDB.HOST);
});

var Histories= new mongoose.Schema({
	id: String,
	from: String,
	to: String,
	message: String,
	read: Boolean,
	created: Number
});

Histories.statics.findAndModify = function (query, columns, doc, options, callback) {
	return this.collection.findAndModify(query, columns, doc, options, callback);
};

var History = db.model(MessengerDB.HISTORY, Histories);

/*
 * Export functions
 */
exports.find = function(condition, fields, constraints, handler) {
	History.find(condition, fields, constraints, function(err, histories) {
		if (err) {
			// TODO: add error handler logic
		}
		
		if (handler) handler(histories);
	});
};

exports.write = function(id, from, to, message) {
	var history = new History({
		id: id,
		from: from,
		to: to,
		message: message,
		read: false,
		created: Number(new Date())
	});
	
	history.save();
};

exports.getHistory = function(from, to, handler) {
	this.getUnreadHistoriesCount(from, to, function(count) {
		var limit = 20;
		if (count > limit) limit = count;
		
		History.find({$or: [{from: from, to: to}, {from: to, to: from}]}, 
				null,
				{limit: limit, sort: {created: -1}}, 
				function(error, histories) {
					// update read to true
					for (var i = 0; i < histories.length; i++) {
						histories[i].read = true;
						histories[i].save();
					}
								
					if (error) {
						// TODO: add error handler logic
					}
					
					if (handler) {
						handler(histories);
					}
			});	
	});	
};

exports.getUnreadHistoriesCount = function(from, to, handler) {
	console.log('get unread..');
	History.count({$or: [{from: from, to: to}, {from: to, to: from}], read: false}, 
		function(error, count) {
			if (error) {
				// TODO: add error handler logic
			}
			
			if (handler) {
				handler(count);
			}
		});
};